import axios, { AxiosInstance, AxiosRequestConfig,AxiosResponse } from "axios";
// const router =useRouter()

let myAxios = axios.create({
    baseURL: "",
    timeout: 5000,
});

myAxios.interceptors.request.use(
    (config) => {
        let token = localStorage.getItem("token");
        if (token && config.headers) {
            config.headers["Authorization"] = token;
        } else {
            config.headers["Authorization"] = "";
        }
        config.headers
            ? (config.headers["Content-Type"] =
                  "application/json;charset=UTF-8")
            : "";
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

myAxios.interceptors.response.use(
    (response) => {
        if (response.data.token) {
            localStorage.setItem("token", "Bearer " + response.data.token);
        }
        return response;
    },
    (err) => {
        if (err && err.response) {
            switch (err.response.status) {
                case 401:
                    console.log("无权限");
                    localStorage.removeItem('token')
                    // navagate('/',{replace:true})
                    // router.replace('/')
                    window.location.reload()
                    break;
                case 404:
                    console.log("请求错误");
                    break;
                default:
                    console.log("网络错误");
                    break;
            }
        }
        return Promise.reject(err);
    }
);

interface BaseResponse<T> {
    code: number
    data: T
    msg:string
    token?:string
}

const request = <T=object>(config: AxiosRequestConfig): Promise<BaseResponse<T>> => {
    return new Promise((resolve, reject) => {
        myAxios.request<BaseResponse<T>>(config).then(
            (res) => {
                resolve(res.data);
            },
            (err) => {
                reject(err);
            }
        );
    });
};
export default request;
